﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using KPIS.GERP.Models;

namespace KPIS.GERP.WCF.ESS
{
	// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "UsersService" in code, svc and config file together.
	// NOTE: In order to launch WCF Test Client for testing this service, please select UsersService.svc or UsersService.svc.cs at the Solution Explorer and start debugging.
	 
	[ServiceContract]
	public interface IUsersService
	{
		[OperationContract]
		bool CheckUserExist(string code, string password);

		[OperationContract]
		bool IsInRoles(string roles, int userId);

	}

	// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "User" in code, svc and config file together.
	// NOTE: In order to launch WCF Test Client for testing this service, please select User.svc or User.svc.cs at the Solution Explorer and start debugging.
	[ServiceErrorBehavior(typeof(ElmahErrorHandler))]
	public class UsersService : IUsersService
	{
		public bool CheckUserExist(string code, string password)
		{
			// current not check password
			using (var db = new GERPContext(false))
			{
				return db.UserProfiles.Any(o => o.UserId.ToString() == code);
			}
		}

		public bool IsInRoles(string roles, int userId)
		{
			roles = roles ?? string.Empty;
			var rolesToCheck = (from r in roles.Split(',') where !string.IsNullOrWhiteSpace(r.Trim()) select r.Trim().ToLower()).ToList();
			if (!rolesToCheck.Any()) return false;
			if (rolesToCheck.Contains("*")) return true;
			List<string> rolesOfThisUser;
			using (var db = new GERPContext(false))
			{
				rolesOfThisUser = (from uir in db.webpages_UsersInRoles
									join r in db.webpages_Roles on uir.RoleId equals r.RoleId
									where uir.UserId == userId
									select r.RoleName.ToLower()).ToList();
			}

			return rolesOfThisUser.Any(rolesToCheck.Contains);
		}
	} 
}
